package com.gxuwz.weather.adapter;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import com.gxuwz.weather.fragment.WeatherFragment;

import java.util.List;

public class WeatherFragmentAdapter extends FragmentStateAdapter {
    private List<String> cityList;

    public WeatherFragmentAdapter(@NonNull FragmentActivity fragmentActivity, List<String> cityList) {
        super(fragmentActivity);
        this.cityList = cityList;
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        WeatherFragment fragment = WeatherFragment.newInstance(cityList.get(position));
        Bundle args = fragment.getArguments();
        if (args == null) args = new Bundle();
        args.putInt("position", position);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getItemCount() {
        return cityList.size();
    }

    /**
     * 更新城市列表并通知适配器数据已更改。
     * 这是确保 ViewPager2 反映最新城市列表的关键方法。
     * @param newCityList 最新的城市列表
     */
    public void updateCityList(List<String> newCityList) {
        this.cityList = newCityList;
        notifyDataSetChanged();// 通知数据已更改
    }
} 